﻿using System;
using System.Drawing;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Media.Imaging;

namespace AndroidSigner.Utils
{
    public static class MethodExtensions
    {
        public static string DeleteSuffix(this string fileName)
        {
            if (!fileName.Contains("."))
            {
                return fileName;
            }

            var lastIndex = fileName.LastIndexOf(".", StringComparison.Ordinal);
            return fileName.Substring(0, lastIndex);
        }

        /// <summary>
        /// 递归删除文件夹
        /// </summary>
        /// <param name="rootDir"></param>
        public static void DeleteDirectory(this string rootDir)
        {
            var dir = new DirectoryInfo(rootDir);
            foreach (var fileInfo in dir.GetFiles())
            {
                fileInfo.Delete();
            }
        }
        
        public static BitmapImage FileToBitmapImage(this string filePath)
        {
            var bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = new MemoryStream(File.ReadAllBytes(filePath));
            bitmapImage.EndInit();
            return bitmapImage;
        }

        public static byte[] FileToImageBuffer(this string filePath)
        {
            //图片转Bitmap
            var bitmap = new Bitmap(filePath);
            //Bitmap转内存缓存
            var stream = new MemoryStream();
            var formatter = new BinaryFormatter();
            formatter.Serialize(stream, bitmap);
            return stream.ToArray();
        }
    }
}